package org.wujiangbo.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wujiangbo.domain.user.User;
import org.wujiangbo.mapper.user.UserMapper;
import org.wujiangbo.query.user.UserQuery;
import org.wujiangbo.result.JSONResult;
import org.wujiangbo.service.user.UserService;
import org.wujiangbo.utils.StringUtils;
import org.wujiangbo.utils.Tools;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author bobo(weixin:javabobo0513)
 * @date 2022-11-02
 */
@Transactional
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    //查询分页列表数据
    public IPage<User> selectMyPage(UserQuery query) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(query.getKeyword())) {
            //下面条件根据实际情况修改
            wrapper.and(
                i -> i.like("user_name", query.getKeyword())
                     .or().like("login_name", query.getKeyword())
            );
        }
        //排序（默认根据主键ID降序排序，根据实际情况修改）
        wrapper.orderByDesc("id");
        Page<User> page = new Page<>(query.getCurrent(), query.getSize());
        return super.page(page, wrapper);
    }

    //查询分页列表数据(自己写SQL)
    public Page<User> selectMySqlPage(UserQuery query) {
        Page<User> page = new Page<>(query.getCurrent(), query.getSize());
        List<User> list = userMapper.selectMySqlPage(page, query);
        return page.setRecords(list);
    }

    @Override
    public JSONResult insertUser1(Integer count) {
        //如果自动提交设置为true，将无法控制提交的条数。所以我这里设置为false，，改为统一提交
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        UserMapper uMapper = session.getMapper(UserMapper.class);
        //获取测试用户集合数据
        List<User> userList = Tools.getUserList(count);
        int commitCount = 5000;//每次提交的数量条数
        long startTime = System.currentTimeMillis();
        for(int i=0; i<userList.size(); i++){
            uMapper.addUserOne(userList.get(i));
            if (i != 0 && i % commitCount == 0) {
                session.commit();
            }
        }
        session.commit();
        long endTime = System.currentTimeMillis();
        log.info("方式1耗时：{}", (endTime - startTime));
        return JSONResult.success();
    }

    @Override
    public JSONResult insertUser2(Integer count) {
        //获取测试用户集合数据
        List<User> userList = Tools.getUserList(count);
        int countItem = 5000;//每次提交的记录条数
        int userSize = userList.size();
        List<User> userListTemp = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        for (int i = 0, n=userSize; i < n; i++) {
            User user= userList.get(i);
            userListTemp.add(user);
            if ((i>0 && i % countItem == 0) || i == userSize - 1) {
                //每5000条记录提交一次
                userMapper.insertUserBatch(userListTemp);
                userListTemp.clear();
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("方式2耗时：{}", (endTime - startTime));
        return JSONResult.success();
    }
    //public JSONResult insertUser2(Integer count) {
    //    //获取测试用户集合数据
    //    List<User> userList = Tools.getUserList(count);
    //    long startTime = System.currentTimeMillis();
    //    //第二个参数：每个子List大小
    //    List<List<User>> users = Lists.partition(userList, 10);
    //    for(int i=0; i<users.size(); i++){
    //        userMapper.insertUserBatch(users.get(i));
    //    }
    //    long endTime = System.currentTimeMillis();
    //    log.info("方式2耗时：{}", (endTime - startTime));
    //    return JSONResult.success();
    //}
}